from server.db.session import with_session
from typing import Dict, List
import uuid
from server.db.models.message_model import MessageModel, CustomMessageModel
from sqlalchemy import and_
from configs import logger
from sqlalchemy.exc import SQLAlchemyError


@with_session
def add_message_to_db(session, conversation_id: str, chat_type, query, response="", message_id=None,
                      metadata: Dict = {}):
    """
    新增聊天记录
    """
    if not message_id:
        message_id = uuid.uuid4().hex
    m = MessageModel(id=message_id, chat_type=chat_type, query=query, response=response,
                     conversation_id=conversation_id,
                     meta_data=metadata)
    session.add(m)
    session.commit()
    return m.id


@with_session
def add_message_to_custom_db(session, user_id: str, conversation_id: str, chat_type: str, query: str, response="",
                             instruction="-1", knowledge_base_name=""):
    """
    新增自定义聊天记录
    """
    try:
        message = CustomMessageModel(user_id=user_id, conversation_id=conversation_id, chat_type=chat_type,
                                     query=query, response=response, instruction=instruction,
                                     knowledge_base_name=knowledge_base_name)
        session.add(message)
        session.commit()
    except SQLAlchemyError as e:
        logger.error(f"Error adding message to custom db: {str(e)}")
    except Exception as e:
        logger.error(f"Error adding message to custom db: {str(e)}")


@with_session
def delete_messages_by_user_id(session, user_id: str):
    """
    删除指定用户的所有聊天记录
    """
    deleted_count = 0
    try:
        # 查询并删除所有匹配user_id的记录
        deleted_count = session.query(CustomMessageModel).\
            filter(CustomMessageModel.user_id == user_id).\
            delete()
        session.commit()
        logger.info(f"删除用户 {user_id} 的聊天记录 {deleted_count} 条")
    except SQLAlchemyError as e:
        session.rollback()
        logger.error(f"SQLAlchemy error deleting messages for user {user_id}: {str(e)}")
    except Exception as e:
        session.rollback()
        logger.error(f"Unexpected error deleting messages for user {user_id}: {str(e)}")
    return deleted_count


@with_session
def update_message(session, message_id, response: str = None, metadata: Dict = None):
    """
    更新已有的聊天记录
    """
    m = get_message_by_id(message_id)
    if m is not None:
        if response is not None:
            m.response = response
        if isinstance(metadata, dict):
            m.meta_data = metadata
        session.add(m)
        session.commit()
        return m.id


@with_session
def get_message_by_id(session, message_id) -> MessageModel:
    """
    查询聊天记录
    """
    m = session.query(MessageModel).filter_by(id=message_id).first()
    return m


@with_session
def get_message_by_user_id(session, user_id, history_len):
    """
    通过user_id查询聊天记录，返回满足条件的格式化记录列表
    """
    try:
        # 优化查询条件，直接在数据库层筛选
        messages = (
            session.query(CustomMessageModel.query, CustomMessageModel.response)
            .filter(
                and_(
                    CustomMessageModel.user_id == user_id,
                    CustomMessageModel.response != '',
                    CustomMessageModel.instruction == "-1"
                )
            )
            .order_by(CustomMessageModel.create_time.desc())
            .limit(history_len)
            .all()
        )

        # 如果没有符合条件的消息，直接返回空列表
        if not messages:
            return []

        # 将查询结果反转，使得最新的消息在最前面
        messages.reverse()

        # 构造最终返回的列表，避免使用 np.concatenate
        result = []
        for message in messages:
            result.extend([
                {"role": "user", "content": message.query},
                {"role": "assistant", "content": message.response}
            ])

        return result
    except SQLAlchemyError as e:
        # 捕获数据库异常，记录日志并返回空列表以确保稳定性
        logger.error(f"Error retrieving messages for user_id {user_id}: {str(e)}")
        return []

    except Exception as e:
        # 捕获任何异常，记录日志并返回空列表以确保稳定性
        logger.error(f"Error retrieving messages for user_id {user_id}: {str(e)}")
        return []


@with_session
def feedback_message_to_db(session, message_id, feedback_score, feedback_reason):
    """
    反馈聊天记录
    """
    m = session.query(MessageModel).filter_by(id=message_id).first()
    if m:
        m.feedback_score = feedback_score
        m.feedback_reason = feedback_reason
    session.commit()
    return m.id


@with_session
def filter_message(session, conversation_id: str, limit: int = 10):
    messages = (session.query(MessageModel).filter_by(conversation_id=conversation_id).
                # 用户最新的query 也会插入到db，忽略这个message record
                filter(MessageModel.response != '').
                # 返回最近的limit 条记录
                order_by(MessageModel.create_time.desc()).limit(limit).all())
    # 直接返回 List[MessageModel] 报错
    data = []
    for m in messages:
        data.append({"query": m.query, "response": m.response})
    return data
